package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TradeStatisticsBean;
import com.atguigu.util.ClickHouseUtil_lj;
import com.atguigu.util.DateFormatUtil_lj;
import com.atguigu.util.MyKafkaUtil_lj;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author 晶晶   1.4.3 交易综合统计  已跑通
 * @Date 2023 03 28 11 05
 **/
public class Dws_TradeTradeStatistics {
    public static void main(String[] args) throws Exception {
        //获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //获取dwd层数据
        String topic = "dwd_trade_order_detail_aa";
        String groupId = "dws_trade_statistics_0926";
        DataStreamSource<String> kafkaDs = env.addSource(MyKafkaUtil_lj.getFinkKafkaConsumer(topic, groupId));

        //转为jsonobject
        SingleOutputStreamOperator<JSONObject> jsonDs = kafkaDs.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null) {
                    out.collect(JSON.parseObject(value));
                }
            }
        });

        //获取watermark
        SingleOutputStreamOperator<JSONObject> dsWithWM = jsonDs.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("create_time");
                    }
                }));

        //key by 分组
        KeyedStream<JSONObject, String> keyedByOdID = dsWithWM.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject value) throws Exception {
                return value.getString("order_id");
            }
        });

        //转为javabean
        SingleOutputStreamOperator<TradeStatisticsBean> beanDs = keyedByOdID.flatMap(new RichFlatMapFunction<JSONObject, TradeStatisticsBean>() {
            private ValueState<String> lastState;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig stateTTL = new StateTtlConfig.Builder(Time.days(1)).setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite).build();
                ValueStateDescriptor<String> stateProperties = new ValueStateDescriptor<String>("last-state", String.class);
                stateProperties.enableTimeToLive(stateTTL);

                lastState = getRuntimeContext().getState(stateProperties);
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradeStatisticsBean> out) throws Exception {
                String ztValue = lastState.value();
                long userCn = 0L;
                if (ztValue == null) {
                    lastState.update("1");
                    userCn = 1L;
                }

                out.collect(TradeStatisticsBean.builder()
                        .OrderAmount(value.getBigDecimal("final_amount"))
                        .orderCount(1L)
                        .userOrderCount(userCn)
                        .build());
            }
        });

        //开窗聚合
        SingleOutputStreamOperator<TradeStatisticsBean> resultDs = beanDs.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .reduce(new ReduceFunction<TradeStatisticsBean>() {
                            @Override
                            public TradeStatisticsBean reduce(TradeStatisticsBean value1, TradeStatisticsBean value2) throws Exception {
                                value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                                value1.setOrderCount(value1.getOrderCount() + value2.getOrderCount());
                                value1.setUserOrderCount(value1.getUserOrderCount() + value2.getUserOrderCount());
                                return value1;
                            }
                        },
                        new AllWindowFunction<TradeStatisticsBean, TradeStatisticsBean, TimeWindow>() {
                            @Override
                            public void apply(TimeWindow window, Iterable<TradeStatisticsBean> values, Collector<TradeStatisticsBean> out) throws Exception {
                                TradeStatisticsBean next = values.iterator().next();
                                next.setTs(System.currentTimeMillis());
                                next.setStt(DateFormatUtil_lj.toYmdHms(window.getStart()));
                                next.setEdt(DateFormatUtil_lj.toYmdHms(window.getEnd()));
                                next.setTs(System.currentTimeMillis());
                                System.out.println(next);
                                out.collect(next);
                            }
                        });

        //写入clickhouse
        resultDs.print(">>>>>>>>>>>>>>>>");
        resultDs.addSink(ClickHouseUtil_lj.getClickHouseSink("insert into dws_trade_statistics values(?,?,?,?,?,?)"));

        //运行任务
        env.execute("Dws_TradeTradeStatistics");

    }
}
